package com.msun.auth.utils;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;


public final class AesUtils {
    private static final String CHARSET_NAME = "UTF-8";
    private static final String AES_NAME = "AES";
    // 加密模式
    public static final String ALGORITHM = "AES/CBC/PKCS7Padding";

    public static final BouncyCastleProvider provider = new BouncyCastleProvider();

    /**
     * 加密
     *
     * @param content
     * @param signKey
     * @return
     */
    public static String encrypt(String content, String signKey) {
        try {
            Security.addProvider(provider);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(signKey.getBytes(StandardCharsets.UTF_8), AES_NAME);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(signKey.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
            byte[] result = cipher.doFinal(content.getBytes(CHARSET_NAME));
            return Base64Encoder.encodeUrlSafe(result);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    /**
     * 解密
     *
     * @param content
     * @param signKey
     * @return
     */
    public static String decrypt(String content, String signKey) throws Exception {
        try {
            Security.addProvider(provider);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(signKey.getBytes(CHARSET_NAME), AES_NAME);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(signKey.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);

            return new String(cipher.doFinal(Base64Decoder.decode(content)), CHARSET_NAME);
        } catch (Exception e) {
            throw e;
        }
    }
}
